﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Data;
using System.Collections.ObjectModel;
using DoubleH.Utility;

namespace ReportS
{
    /// <summary>
    /// 营业额.xaml 的交互逻辑
    /// </summary>
    public partial class 营业额 : Window
    {
        public 营业额()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        private void InitVar()
        {
            uCDateTime1.CanFilterByDate = true;
        }

        private void InitEvent()
        {
            buttonOK.Click += (ss, ee) => FilterData();
        }

        private void FilterData()
        {
           ObservableCollection<Table.ProductSIO> obj = Table.ProductSIO.GetList(uCDateTime1.StartDateTime, uCDateTime1.EndDateTime, true,
                NormalUtility.FormatStringToInt64(checkComboBoxStoreS.SelectedValue), null, Table.ProductSIO.EnumEnable.入账);

            Dictionary<string, List<object>> result = uCDateTime1.FilterData(obj);
            List<TempClass> tc;
            if (radioButtonByJiaoYi.IsChecked.Value)
                tc = FilterByJiaoYi(obj);
            else if (radioButtonByShuLiang.IsChecked.Value)
                tc = FilterByShuLiang(obj);
            else
                tc = FilterDefault(result);
                
                uCdataGrid1.Init(DataTableText.营业额, tc,
                        new UC.CharProperty { Series = new System.Windows.Controls.DataVisualization.Charting.LineSeries(), ValueTitle = "金额", ValueName = "_Money" });
        }
        //营业额/交易次数=平均交易单价
        private List<TempClass> FilterByJiaoYi(ObservableCollection<Table.ProductSIO> obj)
        {
            DataGridColumn drc = uCdataGrid1.dataGridExt1.GetColumn("_Name");
            if (drc != null)
                drc.Header = "商品名称";

            List<TempClass> tc = new List<TempClass>();
            foreach (Table.ProductSIO io in obj)
            {
                if (tc.FirstOrDefault(f => f.Id == io.ProductSId) != null)
                    continue;

                TempClass t = new TempClass();
                t._Name = io._ProductSName;
                t.Id = io.ProductSId;
                var vr = obj.Where(f => f.ProductSId == io.ProductSId);
                t._Money =-Math.Round( vr.Sum(f => f.Price * f.Quantity) /
                    (vr.Distinct(new NormalUtility.Compare<Table.ProductSIO>((x, y) => x.RelatedOrderNO != y.RelatedOrderNO))).Where(f => f.ProductSId == io.ProductSId).Count(),
                    Table.SysConfig.SysConfigParams.DecimalPlaces); ;

                tc.Add(t);
            }
            return tc;
        }
        //营业额/销售数量=产品平均单价
        private List<TempClass> FilterByShuLiang(ObservableCollection<Table.ProductSIO>  obj)
        {
            DataGridColumn drc = uCdataGrid1.dataGridExt1.GetColumn("_Name");
            if (drc != null)
                drc.Header = "商品名称";

            List<TempClass> tc = new List<TempClass>();
            foreach (Table.ProductSIO io in obj)
            {
                if (tc.FirstOrDefault(f => f.Id == io.ProductSId) != null)
                    continue;

                TempClass t = new TempClass();
                t._Name = io._ProductSName;
                t.Id = io.ProductSId;
                var vr = obj.Where(f => f.ProductSId == io.ProductSId);
                t._Money = Math.Round(vr.Sum(f => f.Price * f.Quantity) / vr.Sum(f => f.Quantity), Table.SysConfig.SysConfigParams.DecimalPlaces);
                tc.Add(t);
            }
            return tc;
        }

        private List<TempClass> FilterDefault(Dictionary<string, List<object>> result)
        {
            DataGridColumn drc = uCdataGrid1.dataGridExt1.GetColumn("_Name");
            if (drc != null)
                drc.Header = "日期";

            List<TempClass> tc = new List<TempClass>();
            if (result == null)
                return tc;

            foreach (KeyValuePair<string, List<object>> kp in result)
            {
                TempClass t = new TempClass();
                t._Name = kp.Key;
                foreach (Table.ProductSIO ps in kp.Value)
                    t._Money -= (ps.Price * ps.Quantity);

                if (checkBoxZero.IsChecked.Value && t._Money == 0)
                    continue;

                tc.Add(t);
            }
            return tc;
        }


        public class TempClass
        {
            public Int64 Id { get; set; }
            public string _Name { get; set; }
            public double _Money { get; set; }
        }
        //private void InitVar()
        //{ 
        //    checkComboBoxUserS.DisplayMemberPath = "Name";
        //    checkComboBoxUserS.ValueMemberPath = "Id";
        //    checkComboBoxUserS.ItemsSource = Table.UserS.GetList(null, Table.UserS.EnumFlag.经办人);

        //    checkComboBoxCorS.DisplayMemberPath = "Name";
        //    checkComboBoxCorS.ValueMemberPath = "Id";
        //    checkComboBoxCorS.ItemsSource = MainWindow.allCorS;

        //    if (Table.SysConfig.SysConfigParams.UseSalesOrderS)
        //        checkComboBoxOrderType.Items.Add("批发销售");
        //    if (Table.SysConfig.SysConfigParams.UsePos)
        //        checkComboBoxOrderType.Items.Add("POS零售");
        //    if (Table.SysConfig.SysConfigParams.UseAfterSaleServiceS)
        //        checkComboBoxOrderType.Items.Add("售后维护");
        //}

        //List<TempClass> tc = new List<TempClass>();
        //private void InitEvent()
        //{
        //    buttonOK.Click += (ss, ee) =>
        //        {
        //            List<TempClass> tc = new List<TempClass>();
        //            List<TempClass> result = new List<TempClass>();

        //            if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("批发销售"))
        //                tc.AddRange(GetSalesOrderS());
        //            if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("POS零售"))
        //                tc.AddRange(GetPOS());
        //            if (string.IsNullOrEmpty(checkComboBoxOrderType.Text) || checkComboBoxOrderType.Text.Contains("售后维护"))
        //                tc.AddRange(GetShouHou());

        //            if (checkBoxShowSum.IsChecked.Value)
        //            {
        //                foreach (TempClass t in tc.Distinct(new DoubleH.Utility.NormalUtility.Compare<TempClass>((x, y) => (null != x && null != y) && (x.CorSName.Equals(y.CorSName)))))
        //                {
        //                    var vr = tc.Where(f => f.CorSName == t.CorSName);
        //                    result.Add(new TempClass()
        //                    {
        //                        CorSName = t.CorSName,
        //                        YingYeE = vr.Sum(f => f.YingYeE),
        //                        MaoLi = vr.Sum(f => f.MaoLi)
        //                    });
        //                }
        //                foreach (TempClass t in tc.Distinct(new DoubleH.Utility.NormalUtility.Compare<TempClass>((x, y) => (null != x && null != y) && (x.UserSName.Equals(y.UserSName)))))
        //                {
        //                    var vr = tc.Where(f => f.UserSName == t.UserSName);
        //                    result.Add(new TempClass()
        //                    {
        //                        UserSName = t.UserSName,
        //                        YingYeE = vr.Sum(f => f.YingYeE),
        //                        MaoLi = vr.Sum(f => f.MaoLi)
        //                    });
        //                }
        //            }
        //            else
        //                result = tc;

        //            if (checkBoxHideZero.IsChecked.Value)
        //               result=new List<TempClass>( result.Where(f => f.MaoLi != 0 && f.YingYeE != 0));

        //            uCdataGrid1.Init(DataTableText.营业额,result, new UC.CharProperty() { ValueTitle = "营业额", ValueName = "YingYeE", Series = new System.Windows.Controls.DataVisualization.Charting.LineSeries() },
        //                    new UC.CharProperty() { ValueTitle = "毛利", ValueName = "MaoLi", Series = new System.Windows.Controls.DataVisualization.Charting.LineSeries() });
        //        };
        //}



        //private List<TempClass> GetSalesOrderS()
        //{
        //    List<TempClass> tc = new List<TempClass>();
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("select Result1.*,UserS.Name as UserSName from (select ProductSIO.*,SalesOrderS.UserSId as posUserId, CorS.Name as CorSName from ProductSIO");
        //    sb.Append(" left join CorS on ProductSIO.CorSId=CorS.Id  left join SalesOrderS on SalesOrderS.OrderNO like ProductSIO.RelatedOrderNO  ");
        //    sb.Append(" where ProductSIO.Enable=1 and ProductSIO.RelatedOrderNO like 'PF%' ");
        //    sb.Append(" and cast(ProductSIO.OrderDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(ProductSIO.OrderDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
        //    if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
        //    {
        //        sb.Append(" and (");
        //        foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
        //            sb.Append(" ProductSIO.CorSId=" + str + " or ");

        //        sb.Remove(sb.Length - 3, 3);
        //        sb.Append(")");
        //    }
        //    if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
        //    {
        //        sb.Append(" and (");
        //        foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
        //            sb.Append(" posUserId=" + str + " or ");

        //        sb.Remove(sb.Length - 3, 3);
        //        sb.Append(")");
        //    }
        //    sb.Append(") as Result1 left join UserS on UserS.Id=posUserId");
        //    foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
        //    {
        //        TempClass t = new TempClass();
        //        t.CorSName = row["CorSName"] as string;
        //        t.UserSName = row["UserSName"] as string;
        //        t.YingYeE = (double)row["WholesalePrice"] * (double)row["Quantity"];
        //        t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
        //        tc.Add(t);
        //    }

        //    return tc;
        //    // if (string.IsNullOrEmpty(checkComboBoxUserS.SelectedValue) && string.IsNullOrEmpty(checkComboBoxCorS.SelectedValue))
        //    // {
        //    //     MessageWindow.Show("请选择经办人或者客商");
        //    //     return;
        //    // }

        //    // tc.Clear();
        //    // StringBuilder sb = new StringBuilder(" where Enable=1 and Flag=1");
        //    // if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
        //    // {
        //    //     sb.Append("(");
        //    //     foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
        //    //         sb.Append(" UserSId=" + str + " or ");

        //    //     sb.Remove(sb.Length - 3, 3);
        //    //     sb.Append(")");
        //    // }

        //    // if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
        //    // {
        //    //     sb.Append("(");
        //    //     foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
        //    //         sb.Append(" CorSId=" + str + " or ");

        //    //     sb.Remove(sb.Length - 3, 3);
        //    //     sb.Append(")");
        //    // }
        //    // IList il=new Table.PayS().GetListByWhere("");
        //    //IEnumerable<Table.PayS> ii= Enumerable.Cast<Table.PayS>(il);


        //    //List<UC.CharProperty> cp=new List<UC.CharProperty>();
        //    //if (!string.IsNullOrEmpty(checkComboBoxUserS.SelectedValue))
        //    //{
        //    //    foreach (string str in checkComboBoxUserS.Text.Split(','))
        //    //        cp.Add(new UC.CharProperty()
        //    //        {
        //    //            Series = new System.Windows.Controls.DataVisualization.Charting.ColumnSeries(),
        //    //            ValueName = "Name",
        //    //            ValueTitle = "经办人"
        //    //        });
        //    //}
        //    //else
        //    //    foreach (string str in checkComboBoxCorS.Text.Split(','))
        //    //        cp.Add(new UC.CharProperty()
        //    //        {
        //    //            Series = new System.Windows.Controls.DataVisualization.Charting.ColumnSeries(),
        //    //            ValueName = "Name",
        //    //            ValueTitle = "客商"
        //    //        });


        //    //uCdataGrid1.Init(tc, cp.ToArray());

        //    return tc;
        //}

        //private List<TempClass> GetPOS()
        //{
        //    //Table.ProductSIO.GetList(uCDateTime1.StartDateTime,uCDateTime1.EndDateTime,
        //    List<TempClass> tc = new List<TempClass>();
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("select Result1.*,UserS.Name as UserSName from (select ProductSIO.*,PosOrderS.UserSId as posUserId, CorS.Name as CorSName from ProductSIO");
        //    sb.Append(" left join CorS on ProductSIO.CorSId=CorS.Id  left join PosOrderS on PosOrderS.OrderNO like ProductSIO.RelatedOrderNO  ");
        //    sb.Append(" where ProductSIO.Enable=1 and ProductSIO.RelatedOrderNO like 'POS%' ");
        //    sb.Append(" and cast(ProductSIO.OrderDateTime as varchar) >=" + uCDateTime1.StartDateTimeString + " and cast(ProductSIO.OrderDateTime as varchar) <=" + uCDateTime1.EndDateTimeString);
        //    if (!string.IsNullOrEmpty(checkComboBoxCorS.Text))
        //    {
        //        sb.Append(" and (");
        //        foreach (string str in checkComboBoxCorS.SelectedValue.Split(','))
        //            sb.Append(" ProductSIO.CorSId=" + str + " or ");

        //        sb.Remove(sb.Length - 3, 3);
        //        sb.Append(")");
        //    }
        //    if (!string.IsNullOrEmpty(checkComboBoxUserS.Text))
        //    {
        //        sb.Append(" and (");
        //        foreach (string str in checkComboBoxUserS.SelectedValue.Split(','))
        //            sb.Append(" posUserId=" + str + " or ");

        //        sb.Remove(sb.Length - 3, 3);
        //        sb.Append(")");
        //    }
        //    sb.Append(") as Result1 left join UserS on UserS.Id=posUserId");
        //    foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows(sb.ToString()))
        //    {
        //        TempClass t = new TempClass();
        //        t.CorSName = row["CorSName"] as string;
        //        t.UserSName = row["UserSName"] as string;
        //        t.YingYeE = (double)row["WholesalePrice"] * (double)row["Quantity"];
        //        t.MaoLi = t.YingYeE - (double)row["AveragePrice"] * (double)row["Quantity"];
        //        tc.Add(t);
        //    }

        //    return tc;
        //}

        //private List<TempClass> GetShouHou()
        //{
        //    /*
        //     * 必须是回访结束后才计算，因为可能员工不老实啊。
        //    *毛利=核实后的收费-区域补偿费
        //     */
        //    List<TempClass> tc = new List<TempClass>();
        // var vr=   Table.AfterSaleServiceS.GetList(uCDateTime1.StartDateTime, uCDateTime1.EndDateTime,
        //        NormalUtility.FormatStringToInt64(checkComboBoxCorS.SelectedValue),
        //        NormalUtility.FormatStringToInt64(checkComboBoxUserS.SelectedValue),Table.AfterSaleServiceS.EnumEnable.回访反馈, Table.AfterSaleServiceS.EnumEnable.员工评价);
           
        //    foreach (var v in vr)
        //    {
        //        TempClass t = new TempClass();
        //        t.CorSName = v._CorSName;
        //        t.UserSName = v._ServiceUserSName;
        //        t.YingYeE = v.FuWuFeiHeShi;
        //        t.MaoLi = v.FuWuFeiHeShi;//毛利应该等于营业额-区域补贴给工程师的-工程师报销的 alert
        //        tc.Add(t);
        //    }
        //    return tc;
        //}

        //private class TempClass
        //{
        //    public string CorSName { get; set; }
        //    public string UserSName { get; set; }
        //    public double YingYeE { get; set; }
        //    public double MaoLi { get; set; }
        //}
    }
}
